/*
 * EditContact.java
 *
 * Created on Jul 8, 2010, 10:43:00 PM
 *
 * @author pquiring
 */

import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import javax.swing.*;

import javaforce.voip.*;

public class EditContact extends javax.swing.JDialog {

  /** Creates new form EditContact */
  private EditContact(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    setPosition();
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        name = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        number = new javax.swing.JTextField();
        monitor = new javax.swing.JCheckBox();
        save = new javax.swing.JButton();
        cancel = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        server = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Name:");

        name.setText("name");

        jLabel2.setText("Number:");

        number.setText("number");

        monitor.setText("Monitor Availability Changed");

        save.setText("Save");
        save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveActionPerformed(evt);
            }
        });

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        jLabel3.setText("Server:");

        server.setText("server");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(monitor)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(save)
                                .addGap(18, 18, 18)
                                .addComponent(cancel)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(server)
                            .addComponent(name, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
                            .addComponent(number, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(server, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(monitor)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(save)
                    .addComponent(cancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

  private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
    if (!valid()) {
      return;
    } else {
      dispose();
    }
  }//GEN-LAST:event_saveActionPerformed

  private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
    cancelled = true;
    dispose();
  }//GEN-LAST:event_cancelActionPerformed

  /**
  * @param args the command line arguments
  */
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        EditContact dialog = new EditContact(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JCheckBox monitor;
    private javax.swing.JTextField name;
    private javax.swing.JTextField number;
    private javax.swing.JButton save;
    private javax.swing.JTextField server;
    // End of variables declaration//GEN-END:variables

  private static boolean cancelled = false;
  private String fields[];
  private boolean newContact;

  /** Pops up the EditContact dialog window and returns when the dialog is closed. */

  public static String editContact(java.awt.Frame parent, String contact, boolean newContact) {
    EditContact dialog = new EditContact(parent, true);
    dialog.fields = SIP.split(contact);
    dialog.name.setText(dialog.fields[0]);
    dialog.number.setText(dialog.fields[1]);
    dialog.server.setText(dialog.fields[2]);
    dialog.monitor.setSelected( SIP.getFlag2(dialog.fields, "monitor").equals("true") );
    dialog.newContact = newContact;

    dialog.setVisible(true);  //doesn't return until dialog is closed

    if (cancelled) return null;
    dialog.fields[0] = dialog.name.getText();
    dialog.fields[1] = dialog.number.getText();
    dialog.fields[2] = dialog.server.getText();
    dialog.fields = SIP.setFlag2(dialog.fields, "monitor", (dialog.monitor.isSelected() ? "true" : "false"));
    return SIP.join(dialog.fields);
  }

  private void validateName() {
//System.out.println("validateName");
    //make sure name doesn't contain certain chars
    String text = name.getText();
    String newtext = "";
    boolean clean = true;
    char ch;
    for(int a=0;a<text.length();a++) {
      ch = text.charAt(a);
      switch (ch) {
        case '@':
        case '<':
        case '>':
        case '!':
        case ';':
        case ':':
        case '\'':
        case '\"':
          clean = false;
          break;
        default:
          newtext += ch;
          break;
      }
    }
    if (clean) return;
    name.setText(newtext);
  }

  private void validateNumber() {
    //make sure number has only numbers
    String text = number.getText();
    String newtext = "";
    boolean clean = true;
    char ch;
    for(int a=0;a<text.length();a++) {
      ch = text.charAt(a);
      if ((ch >= '0') && (ch <= '9')) {
        newtext += ch;
        continue;
      }
      clean = false;
    }
    if (clean) return;
    number.setText(newtext);
  }

  private void validateServer() {
    //make sure server has only alpha,numeric and '.', '-'
    String text = server.getText();
    String newtext = "";
    boolean clean = true;
    char ch;
    for(int a=0;a<text.length();a++) {
      ch = text.charAt(a);
      if ((ch >= '0') && (ch <= '9')) {
        newtext += ch;
        continue;
      }
      if ((ch >= 'a') && (ch <= 'z')) {
        newtext += ch;
        continue;
      }
      if ((ch >= 'A') && (ch <= 'Z')) {
        newtext += ch;
        continue;
      }
      switch (ch) {
        case '.':
        case '-':
        case ':':
          newtext += ch;
          continue;
        default:
          clean = false;
          break;
      }
    }
    if (clean) return;
    server.setText(newtext);
  }

  private void msg(String msg) {
    JOptionPane.showMessageDialog(this, msg, "Error", JOptionPane.ERROR_MESSAGE);
  }

  private boolean valid() {
    validateName();
    validateNumber();
    validateServer();
    if (name.getText().length() == 0) {msg("Invalid name"); return false;}
    if (number.getText().length() == 0) {msg("Invalid number"); return false;}
    if (server.getText().equals(":")) {msg("Invalid server"); return false;}  //this would cause issues with SIP.split()/join()
    if (monitor.isSelected() && (server.getText().length() == 0)) {msg("Invalid server"); return false;}
    //check if name has changed and already exists
    if ((newContact) || (!name.getText().equals(fields[0]))) {
      for(int a=0;a<Settings.current.sipcontacts.length;a++) {
        String sipfields[] = SIP.split(Settings.current.sipcontacts[a]);
        if (name.getText().equals(sipfields[0])) {
          msg("That contact already exists, choose a different name");
          return false;
        }
      }
    }
    return true;
  }
  private void setPosition() {
    Dimension d = getSize();
    Rectangle s = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
    setLocation(s.width/2 - d.width/2, s.height/2 - d.height/2);
  }
}
